// pages/chat/chat.ts
import { isLogin, login } from '../../utils/login'
import { getCaseList, getMyCaseList } from '../../api/case'
import { formatTime } from '../../utils/util'
import { getTrainTaskData, getTrainProjectList } from '../../api/train'

Page({
  /**
   * 页面的初始数据
   */
  data: <any>{
    active: 1,
    showJoinWebinarDialog: false,
    currentWebinar: {},
    case: {
      pageNum: 1,
      pageSize: 200,
      name: ''
    },
    caseList: [],
    mycase: {
      pageNum: 1,
      pageSize: 10,
      name: ''
    },
    myCaseList: [],
    professerList: [],
    projectList: [],
    score: {
      totalNum: 0,
      incompleteNum: 0,
      diffRate: 0
    },
    project: {
      pageNum:1,
      pageSize: 200,
      name: ''
    }
  },

  onLoad(){
    this.init()
  },

  onShow(){
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 2
      })
    }

    if(isLogin()){
      this.getProjectList()
    }
  },

  init(){
    if(isLogin()){
      const userInfo = login()
      if(userInfo){
        this.handleLoginAction(userInfo);
        this.getCase()
        this.getTrainData()
        this.getProjectList()
      }
    }
  },

  handleLoginAction(userInfo: any){
    this.setData({
      userInfo: userInfo,
      logined: true,
    })
  },

  onSearch(){
    console.log('---触发搜索')
  },

  inputHandle(e: any){
    const value = e.detail.value;
    this.setData({
      content: value
    })
    if(value === ''){
      setTimeout(() => {
        this.searchHandle({
          detail: {
            value: ''
          }
        })
      }, 0)
    }
  },

  searchClick(){
    setTimeout(() => {
      this.searchHandle({
        detail: {
          value: this.data.content
        }
      })
    }, 100)
  },

  searchHandle(e: any){
    const value = e.detail.value.trim();
    this.setData({
      content: value
    })
    
    const caseAction = this.getType(this.data.active);
    const data: any = {};
    data[caseAction.listName] = []
    data[caseAction.type] = {
      name: value
    }
    this.setData(data)
    setTimeout(() => {
      caseAction.api()
    }, 0)
    e.stopPropagation()
  },

  searchTaskHandle(e: any){
    console.log('---触发搜索项目')

    const value = e.detail.value;
    const caseAction = this.getType(this.data.active);
    const data: any = {};
    data[caseAction.listName] = []
    data[caseAction.type] = {
      name: value
    }
    this.setData(data)

    setTimeout(() => {
      caseAction.api()
    }, 0)
    e.stopPropagation()
  },

  getCase(){
    getCaseList(this.data.case).then((res: any) => {
      if(res && res.rows.length > 0){
        const rows = res.rows.map((item: any) => {
          const conferenceVo = item.conferenceVo
          const caseItem = {
            ...item,
            // diagnosisTime: formatDate(new Date(item.diagnosisTime))
          }
          if(conferenceVo){
            caseItem.conferenceVo = {
              ...item.conferenceVo,
              openTime: formatTime(new Date(item.conferenceVo.openTime)),
            }
          }
          return caseItem
        })
        this.setData({
          caseList: [
            ...this.data.caseList,
            ...rows
          ]
        })
        if(res.rows.length === this.data.case.pageSize){
          const pageNum = this.data.case.pageNum
          this.setData({
            case: {
              pageNum: pageNum + 1
            }
          })
        }
      }
    })
  },

  getMyCase(){
    getMyCaseList(this.data.mycase).then((res: any) => {
      if(res && res.rows.length > 0){
        const rows = res.rows.map(item => {
          const conferenceVo = item.conferenceVo
          const caseItem = {
            ...item,
            // diagnosisTime: formatTime(new Date(item.diagnosisTime))
          }
          if(conferenceVo){
            caseItem.conferenceVo = {
              ...item.conferenceVo,
              openTime: formatTime(new Date(item.conferenceVo.openTime)),
            }
          }
          return caseItem
        })
        this.setData({
          myCaseList: [
            ...this.data.myCaseList,
            ...rows
          ]
        })
        if(res.rows.length === this.data.mycase.pageSize){
          const pageNum = this.data.mycase.pageNum
          this.setData({
            mycase: {
              pageNum: pageNum + 1
            }
          })
        }
      }
    })
  },

  getTrainData(){
    getTrainTaskData().then((res: any) => {
      if(res && res.data){
        const {totalNum, incompleteNum, diffRate} = res.data
        this.setData({
          score: {
            totalNum, incompleteNum, diffRate: Number(diffRate).toFixed(1)
          }
        })
      }
    })
  },

  getProjectList(){
    getTrainProjectList({
      pageNum: this.data.project.pageNum,
      pageSize: this.data.project.pageSize,
      taskName: this.data.project.name
    }).then((res: any) => {
      if(res && res.rows.length > 0){
        this.setData({
          projectList: res.rows
        })
      }
    })
  },

  caseHandle(data: any){
    const index = data.currentTarget.dataset.index as string
    this.setData({
      active: index
    })
  
    setTimeout(() => {
      const caseAction = this.getType(index);
      if(caseAction.rule === 'once'){
        if(caseAction.list.length === 0){
          caseAction.api()
        }
      }else{
        caseAction.api()
      }

      if(index === '3'){
        this.getTrainData()
      }
    }, 0)
  },

  createCaseHandle(){
    wx.navigateTo({
      url: '/pages/createQuestion/createQuestion',
      events: {
        acceptDataFromOpenerPage: function (data: any) {
          console.log(data)
        }
      },
      success: (res) => {
        res.eventChannel.emit('acceptDataFromOpenerPage', {
          data: {
            id: 1
          }
        })
      }
    });
  },

  openDetail(e: any){
    wx.navigateTo({
      url: '/pages/caseDetail/caseDetail',
      success: (res) => {
        res.eventChannel.emit('acceptDataFromOpenerPage', e.currentTarget.dataset.item)
      }
    });
  },

  openTrainProjectDetail(e: any){
    const data = e.currentTarget.dataset.item;
    const currDate = new Date().toISOString().slice(0, 10)
    const start = new Date(data.beginDate);
    const end = new Date(data.endDate);
    const now = new Date(currDate);

    if(now < start){
      wx.showToast({
        title: '项目还未开始',
        icon: 'none'
      });
      return;
    }

    if(now > end){
      wx.showToast({
        title: '项目已经结束',
        icon: 'none'
      });
      return;
    }

    wx.navigateTo({
      url: '/pages/project/project?title=' + data.name,
      success: (res) => {
        res.eventChannel.emit('acceptDataFromOpenerPage', e.currentTarget.dataset.item)
      }
    });
  },

  joinHandle(data: any){
    const conference = data.currentTarget.dataset.conference

    this.setData({
      currentWebinar: conference,
      showJoinWebinarDialog: true
    })
  },

  closeJoinWebinarDialog(){
    this.setData({
      showJoinWebinarDialog: false
    })
  },

  refresh(type: string){
    this.setData({
      myCaseList: [],
      mycase: {
        pageNum: 1
      }
    })
    const caseAction = this.getType(type);
    caseAction.api()
  },

  getType(type: string){
    const caseAction: any = {
      '1': {
        type: 'case',
        listName: 'caseList',
        list: this.data.caseList,
        api: this.getCase,
        rule: 'once'
      },
      '2': {
        type: 'myCase',
        listName: 'myCaseList',
        list: this.data.myCaseList,
        api: this.getMyCase,
        rule: 'once'
      },
      '3': {
        type: 'project',
        listName: 'projectList',
        list: this.data.projectList,
        api: this.getProjectList,
      },
    };
    return caseAction[type]
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    try {
      this.data.requestTask.abort()
    } catch (error) {
      console.log('还没发请求就退出了，正常不会有影响')
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      "title": "",
      "path": `pages/home/home?active=1`,
      "imageUrl": "/static/img/home.jpg"
    }
  }
})